//
//  AddBankCardVC.m
//  MRBang
//
//  Created by 铅笔 on 16/4/20.
//  Copyright © 2016年 杭州易网新科技. All rights reserved.
//

#import "AddBankCardVC.h"

#import "PickViewSelect.h"

#define CELLHEIGHT 125*PROPORTION_WIDTH

@interface AddBankCardVC ()<UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate,pickViewStrDelegate>
{
    UIButton *button_sureAdd;//确认添加
    UILabel *label_nameBank;
    NSString *pathBankId;//传递 银行卡代码号
}

@property (nonatomic,strong) UITableView *tableView_addBankCard;
@property (nonatomic,strong) UITextField *textField_name;
@property (nonatomic,strong) UITextField *textField_cardNum;
@property (nonatomic,strong) UITextField *textField_idCard;
@property (nonatomic,strong) UITextField *textField_telphone;
@property (nonatomic,strong) UITextField *textField_checkCode;
@property (nonatomic,strong) UIButton *button_getCheckCode;

@property(nonatomic,strong) PickViewSelect *pickView;

@end

@implementation AddBankCardVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"添加银行卡";
    
    pathBankId = @"";
    
    self.view.backgroundColor = COLOR_EVERYVIEWBG;
    
    [self initWithAddBankCardVCSubviews];
    
    //注册键盘通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}

#pragma mark --- 创建明细表
- (void) initWithAddBankCardVCSubviews
{
    self.tableView_addBankCard = [[UITableView alloc] initWithFrame:CGRectMake(0,0, kScreenWidth,CELLHEIGHT*6+10)];
    [self.view addSubview:self.tableView_addBankCard];
    self.tableView_addBankCard.dataSource = self;
    self.tableView_addBankCard.delegate = self;
    self.tableView_addBankCard.showsVerticalScrollIndicator = NO;
    self.tableView_addBankCard.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView_addBankCard.scrollEnabled = NO;
    self.tableView_addBankCard.backgroundColor = COLOR_EVERYVIEWBG;
    
    //button  add card
    button_sureAdd = [[UIButton alloc] initWithFrame:CGRectMake(30*PROPORTION_WIDTH,self.tableView_addBankCard.bottom+55*PROPORTION_WIDTH, kScreenWidth-30*2*PROPORTION_WIDTH, 95*PROPORTION_WIDTH)];
    [self.view addSubview:button_sureAdd];
    [button_sureAdd setImage:[UIImage imageNamed:@"button_sureAdd"] forState:UIControlStateNormal];
    [button_sureAdd addTarget:self action:@selector(rechargeAndWithdrawsAction) forControlEvents:UIControlEventTouchUpInside];
}

//确认绑定 银行卡
- (void) rechargeAndWithdrawsAction
{
    [self commentTableViewTouchInSide];
    [self DataSourceRequestAddBankCardVCView];
}

#pragma mark --- UITableViewDataSource
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 5;
//    return 4;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellMyTradingRecordID = @"cellMyTradingRecordID";
    UITableViewCell *cell_recharge = [tableView cellForRowAtIndexPath:indexPath];
    if (cell_recharge == nil) {
        cell_recharge = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellMyTradingRecordID];
    }
    
    cell_recharge.selectionStyle = UITableViewCellSelectionStyleNone;
    
    //line
    UIView *view_line = [[UIView alloc] initWithFrame:CGRectMake(27*PROPORTION_WIDTH, CELLHEIGHT-1, kScreenWidth, 1.0)];
    [cell_recharge.contentView addSubview:view_line];
    view_line.backgroundColor = [BaseViewController colorWithHexString:@"#EEEFF1"];

    //label
    UILabel *label_leftTitle = [[UILabel alloc] init];
    [cell_recharge.contentView addSubview:label_leftTitle];
    label_leftTitle.font = [UIFont systemFontOfSize:24*PROPORTION_WIDTH];
    label_leftTitle.textColor = [BaseViewController colorWithHexString:@"#384056"];
     label_leftTitle.frame = CGRectMake(44*PROPORTION_WIDTH, 50*PROPORTION_WIDTH, 130*PROPORTION_WIDTH, 31*PROPORTION_WIDTH);
    
    NSArray *array_title = @[@"持卡人",@"银行卡名称",@"银行卡卡号",@"身份证号",@"预留手机号"];
//    if (indexPath.row!=4) {
    
        label_leftTitle.text = array_title[indexPath.row];
//    }
    
    if (indexPath.row==0) {
        //textfield
        self.textField_name = [[UITextField alloc] initWithFrame:CGRectMake(label_leftTitle.right+35*PROPORTION_WIDTH, label_leftTitle.y, 550*PROPORTION_WIDTH, label_leftTitle.height)];
        [cell_recharge.contentView addSubview:self.textField_name];
        self.textField_name.placeholder = @"请输入持卡人姓名";
        self.textField_name.font = [UIFont systemFontOfSize:24*PROPORTION_WIDTH];
        
    }

    if (indexPath.row==1) {
        
        //button
        UIButton *button_rightArrow = [[UIButton alloc] initWithFrame:CGRectMake(kScreenWidth-50*PROPORTION_WIDTH, 47*PROPORTION_WIDTH, 30*PROPORTION_WIDTH, 34*PROPORTION_WIDTH)];
        [cell_recharge.contentView addSubview:button_rightArrow];
        [button_rightArrow setImage:[UIImage imageNamed:@"return_right"] forState:UIControlStateNormal];
        
        //label
        label_nameBank = [[UILabel alloc] init];
        [cell_recharge.contentView addSubview:label_nameBank];
        label_nameBank.font = [UIFont systemFontOfSize:24*PROPORTION_WIDTH];
        label_nameBank.textColor = [BaseViewController colorWithHexString:@"#384056"];
        label_nameBank.frame = CGRectMake(30*PROPORTION_WIDTH+label_leftTitle.right, 50*PROPORTION_WIDTH, 330*PROPORTION_WIDTH, 31*PROPORTION_WIDTH);
        
    }
    if (indexPath.row==2) {
        //textfield
        self.textField_cardNum = [[UITextField alloc] initWithFrame:CGRectMake(label_leftTitle.right+35*PROPORTION_WIDTH, label_leftTitle.y, 550*PROPORTION_WIDTH, label_leftTitle.height)];
        [cell_recharge.contentView addSubview:self.textField_cardNum];
        self.textField_cardNum.placeholder = @"请输入银行卡卡号";
        self.textField_cardNum.keyboardType = UIKeyboardTypeNumberPad;
        self.textField_cardNum.font = [UIFont systemFontOfSize:24*PROPORTION_WIDTH];
        self.textField_cardNum.delegate = self;
        [self.textField_cardNum addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];

    }
    if (indexPath.row==3) {
        
        //textfield
        self.textField_idCard = [[UITextField alloc] initWithFrame:CGRectMake(label_leftTitle.right+35*PROPORTION_WIDTH, label_leftTitle.y, 550*PROPORTION_WIDTH, label_leftTitle.height)];
        [cell_recharge.contentView addSubview:self.textField_idCard];
        self.textField_idCard.placeholder = @"请输入身份证号";
        
        self.textField_idCard.font = [UIFont systemFontOfSize:24*PROPORTION_WIDTH];
        self.textField_idCard.delegate = self;
        [self.textField_idCard addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    }
    if (indexPath.row==4) {
        
        //textfield
        self.textField_telphone = [[UITextField alloc] initWithFrame:CGRectMake(label_leftTitle.right+35*PROPORTION_WIDTH, label_leftTitle.y, 550*PROPORTION_WIDTH, label_leftTitle.height)];
        [cell_recharge.contentView addSubview:self.textField_telphone];
        self.textField_telphone.placeholder = @"请输入预留手机号";
        self.textField_telphone.keyboardType = UIKeyboardTypeNumberPad;
        self.textField_telphone.font = [UIFont systemFontOfSize:24*PROPORTION_WIDTH];
        self.textField_telphone.tag = 1102;
        self.textField_telphone.delegate = self;
        
        [self.textField_telphone addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
        
    }
//    if (indexPath.row==4) {
    
        //button
//        self.button_getCheckCode = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 210*PROPORTION_WIDTH, CELLHEIGHT)];
//        [cell_recharge.contentView addSubview:self.button_getCheckCode];
//        self.button_getCheckCode.backgroundColor = COLOR_BUTTON;
//        [self.button_getCheckCode setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
//        [self.button_getCheckCode setTitle:@"获取验证码" forState:UIControlStateNormal];
//        [self.button_getCheckCode.titleLabel setFont:[UIFont systemFontOfSize:24*PROPORTION_WIDTH]];
        
        //textfield
//        self.textField_checkCode = [[UITextField alloc] initWithFrame:CGRectMake(self.button_getCheckCode.right+35*PROPORTION_WIDTH, label_leftTitle.y, 550*PROPORTION_WIDTH, label_leftTitle.height)];
//        [cell_recharge.contentView addSubview:self.textField_checkCode];
//        self.textField_checkCode.placeholder = @"请输入验证码";
//        self.textField_checkCode.keyboardType = UIKeyboardTypeNumberPad;
//        self.textField_checkCode.font = [UIFont systemFontOfSize:24*PROPORTION_WIDTH];
//    }
    
    return cell_recharge;
}

- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self commentTableViewTouchInSide];
    if (indexPath.row==1) {
//        NSArray *array_allData = @[@"工商银行",@"中国农业银行",@"中国建设银行",@"招商银行",@"交通银行",@"中国邮政储蓄银行",@"农村信用合作社",@"中信银行",@"兴业银行",@"中国光大银行",@"华夏银行",@"深圳发展银行",@"中国民生银行",@"平安银行",@"中国银行"];
        
         NSArray *array_allData = @[@"中国工商银行",@"中国农业银行",@"中国建设银行",@"招商银行",@"交通银行",@"中国邮政储蓄银行",@"中信银行",@"兴业银行",@"中国光大银行",@"中国银行",@"浦发银行"];
        
        _pickView =[[PickViewSelect alloc]initWithDataArr:array_allData andRowIndex:1];
        _pickView.delegate = self;
        [self.view addSubview:_pickView];
    }
}

- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return CELLHEIGHT;

}

#pragma mark -- picker delegate
- (void) pickViewdelegateWith:(NSString *)messStr andRow:(int)rowIndex andSelectecRow:(int)selectedRow
{
    
    NSLog(@"messStr%@",messStr);
    if ([messStr isEqualToString:@"中国工商银行"]) {
        pathBankId = @"0102";
    }
    if ([messStr isEqualToString:@"中国农业银行"]) {
        pathBankId = @"0103";
    }
    if ([messStr isEqualToString:@"中国建设银行"]) {
        pathBankId = @"0105";
    }
    if ([messStr isEqualToString:@"招商银行"]) {
        pathBankId = @"0308";
    }
    if ([messStr isEqualToString:@"交通银行"]) {
        pathBankId = @"0301";
    }
    if ([messStr isEqualToString:@"中国邮政储蓄银行"]) {
        pathBankId = @"0403";
    }
//    if ([messStr isEqualToString:@"农村信用合作社"]) {
//        pathBankId = @"0402";
//    }
    if ([messStr isEqualToString:@"中信银行"]) {
        pathBankId = @"0302";
    }
    if ([messStr isEqualToString:@"兴业银行"]) {
        pathBankId = @"0309";
    }
    if ([messStr isEqualToString:@"中国光大银行"]) {
        pathBankId = @"0303";
    }
//    
//    if ([messStr isEqualToString:@"华夏银行"]) {
//        pathBankId = @"0304";
//    }
//    if ([messStr isEqualToString:@"深圳发展银行"]) {
//        pathBankId = @"0307";
//    }
//    if ([messStr isEqualToString:@"中国民生银行"]) {
//        pathBankId = @"0305";
//    }
//    if ([messStr isEqualToString:@"平安银行"]) {
//        pathBankId = @"0307";
//    }
    if ([messStr isEqualToString:@"中国银行"]) {
        pathBankId = @"0104";
    }




    
    label_nameBank.text = messStr;
}

/**
 *键盘是否亮起
 */
- (void)textFieldDidChange:(UITextField *)textField
{
    if (textField==self.textField_telphone) {
        if (self.textField_telphone.text.length>10) {
            textField.text = [textField.text substringToIndex:11];
        }
    }
    //身份证号
    if (textField==self.textField_idCard) {
        if (self.textField_idCard.text.length>17) {
            textField.text = [textField.text substringToIndex:18];
        }
    }

    if (textField==self.textField_cardNum) {
        if (self.textField_cardNum.text.length>29) {
            textField.text = [textField.text substringToIndex:30];
        }
    }
}

#pragma mark  --- 点击tableView 收回键盘
- (void)commentTableViewTouchInSide{
    [self.textField_cardNum resignFirstResponder];
    [self.textField_checkCode resignFirstResponder];
    [self.textField_name resignFirstResponder];
    [self.textField_telphone resignFirstResponder];
    [self.textField_idCard resignFirstResponder];
}

- (void) touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.textField_cardNum endEditing:YES];
    [self.textField_checkCode endEditing:YES];
    [self.textField_name endEditing:YES];
    [self.textField_telphone endEditing:YES];
    [self.textField_idCard endEditing:YES];
}

#pragma mark -- 网络数据请求
//添加（绑定）银行卡
- (void) DataSourceRequestAddBankCardVCView
{
    if (self.textField_telphone.text.length==0 || self.textField_name.text==0 || self.textField_cardNum.text.length==0 || label_nameBank.text.length==0) {
        
        [UIView showAlertMsg:@"请完善信息"];
        
        return;
    }
    
    if (![BaseViewController isMobileNumber_str:self.textField_telphone.text]) {
        [UIView showAlertMsg:@"手机号码有误，请查看"];
        
        return;
    }
    
    if (![BaseViewController checkIdentityCardNo:self.textField_idCard.text]) {
        [UIView showAlertMsg:@"请输入正确身份证码"];
        
        return;
    }
    
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    Reachability *reach = [Reachability reachabilityForInternetConnection];
    NetworkStatus status = [reach currentReachabilityStatus];
    
    if (![UIView NetFromStatus:status]) {
        NSLog(@"没有网络");
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
        [UIView showAlertMsg:@"网络连接已断开" andShowBgColor:[UIColor blackColor] andLabelTectColor:[UIColor whiteColor]];
        
        return;
    }
    else
    {
        //绑定银行卡
        NSString *strUrl = [NSString stringWithFormat:@"%@member/bdbank",MRAPI];
        
//        label_nameBank.text = @"中国工商银行";
//        self.textField_cardNum.text = @"6217000340000565982";
//        self.textField_name.text = @"杨晓晖";
//        self.textField_idCard.text = @"110101198601040010";
//        self.textField_telphone.text = @"15005811687";
        
        NSLog(@"pathBankId%@",pathBankId);
        
        NSDictionary *paras_loan = @{@"memberid":[[NSUserDefaults standardUserDefaults] objectForKey:@"memberid"],@"bankname":label_nameBank.text,@"banknum":self.textField_cardNum.text,@"bankusername":self.textField_name.text,@"idcard":self.textField_idCard.text,@"mobile":self.textField_telphone.text,@"bankdaima":pathBankId};
        
        [[HttpRequest shardWebUtil] postNetworkRequestURLString:strUrl parameters:paras_loan success:^(id obj) {
            
            [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
            
            NSLog(@"member/bdbank%@--%@",obj,obj[@"error"]);
            
            NSString *str_false = obj[@"error"];
            
            if (str_false.length==0) {
                [UIView showAlertMsg:@"添加成功"];
                [self.navigationController popViewControllerAnimated:YES];
            }
            else
            {
                [BaseViewController showMessage:str_false];
            }
            
        } fail:^(NSError *error) {
            NSLog(@"get%@",error);
            
            [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
            [UIView showAlertMsg:@"网络请求超时"];
            
        }];
        
    }
}

#pragma mark keyboardNotification

- (void)keyboardWillShow:(NSNotification*)notification{
    CGRect _keyboardRect = [[[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    //如果self在键盘之下 才做偏移
    if ([self convertYToWindow:CGRectGetMaxY(self.textField_checkCode.frame)]>=_keyboardRect.origin.y)
    {
        //没有偏移 就说明键盘没出来，使用动画
        if (self.view.frame.origin.y== self.textField_checkCode.frame.origin.y) {
            
            [UIView animateWithDuration:0.3 animations:^{
                self.view.frame = CGRectMake(0, -_keyboardRect.size.height+[self getHeighOfWindow]-CGRectGetMaxY(self.view.frame), kScreenWidth, kScreenHeight);
            }];
        }
        else
        {
            self.view.frame = CGRectMake(0, -50, kScreenWidth, kScreenHeight);
        }
    }
}

- (void)keyboardWillHide:(NSNotification*)notification{
    
    [UIView animateWithDuration:0.3 animations:^{
        self.view.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
    }];
}

#pragma  mark ConvertPoint
//将坐标点y 在window和superview转化  方便和键盘的坐标比对
-(float)convertYFromWindow:(float)Y
{
    AppDelegate *appDelegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
    CGPoint o = [appDelegate.window convertPoint:CGPointMake(0, Y) toView:self.view];
    return o.y;
    
}
-(float)convertYToWindow:(float)Y
{
    AppDelegate *appDelegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
    CGPoint o = [self.view convertPoint:CGPointMake(0, Y) toView:appDelegate.window];
    return o.y;
    
}
-(float)getHeighOfWindow
{
    AppDelegate *appDelegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
    return appDelegate.window.frame.size.height;
}

-(void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
   
}



@end
